const arrayToTree = (data, type) => {
  let result = [];
  let itemMap = {};
  for (let i = 0; i < data.length; i++) {
    let item = data[i];
    let id = type == "pid" ? item.id : item["编码"];
    let pid = type == "pid" ? item.pid : item["父节点编码"];
    if (!itemMap[id]) {
      itemMap[id] = {
        children: [],
      };
    }
    itemMap[id] = {
      ...item,
      children: itemMap[id]["children"],
    };
    let treeItem = itemMap[id];
    if (pid === null) {
      result.push(treeItem);
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = {
          children: [],
        };
      }
      itemMap[pid]["children"].push(treeItem);
    }
  }
  return result;
};
function convertToTree(data) {
  let tempdata = data;
  for (let i = 0; i < tempdata.length; i++) {
    const item = tempdata[i];
    let path = item["编码"].split("-");
    if (path.length > 1) {
      item["id"] = path.join();
      item["pid"] = path.slice(0, path.length - 1).join();
    } else {
      item["id"] = path.join();
      item["pid"] = null;
    }
  }
  return arrayToTree(tempdata, "pid");
}
export { arrayToTree, convertToTree };
